package com.ks.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.TransportMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * redission配置
 *
 * @author KingAusten
 * @date 2022/08/17 16:57:15
 */
@Configuration
public class RedissionConfiguration{

    /**
     * 核心池大小
     */
    private static final int CORE_POOL_SIZE = Runtime.getRuntime()
            .availableProcessors();

    /**
     * redis主机
     */
    @Value("${spring.redis.host}")
    private String redisHost;

    /**
     * redis 端口
     */
    @Value("${spring.redis.port}")
    private String redisPort;

    /**
     * redis 密码
     */
    @Value("${spring.redis.password}")
    private String redisPwd;

    /**
     * redisson客户端
     *
     * @return {@link RedissonClient }
     */
    @Bean
    public RedissonClient redissonClient(){

        Config config = new Config();
        //单机方式
        config.useSingleServer()
                .setPassword(redisPwd)
                .setAddress("redis://" + redisHost + ":" + redisPort);
        //使用 jackJson 序列化器
        config.setCodec(new JsonJacksonCodec());
        config.setTransportMode(TransportMode.NIO);
        config.setThreads(CORE_POOL_SIZE << 1);
        config.setNettyThreads(CORE_POOL_SIZE << 1);
        config.setExecutor(new ThreadPoolExecutor(CORE_POOL_SIZE << 1,CORE_POOL_SIZE << 1,0L,TimeUnit.SECONDS,new ArrayBlockingQueue<>(1000),Executors.defaultThreadFactory(),
                                                  new ThreadPoolExecutor.AbortPolicy()));
        return Redisson.create(config);
    }

}
